<template>
  <div class="update-profile">
    <h3>更新个人信息</h3>
    <form  @submit.prevent="handleUpdateProfile">
      <div class="form-group">
        <label for="name">姓名:</label>
        <input
            type="text"
            id="name"
            v-model="userInfo.username"
            placeholder="请输入用户名"
            required
            @focus="clearInput('username')"
            @blur="restorePlaceholder('username')"
        />
      </div>
      <div class="form-group">
        <label for="name">年龄:</label>
        <input
            type="number"
            id="age"
            v-model="userInfo.age"
            placeholder="请输入年龄"
            @focus="clearInput('age')"
            @blur="restorePlaceholder('age')"
        />
      </div>
      <div class="form-group">
        <label for="email">邮箱:</label>
        <input
            type="email"
            id="email"
            v-model="userInfo.email"
            placeholder="请输入邮箱"
            required
            @focus="clearInput('email')"
            @blur="restorePlaceholder('email')"
        />
      </div>      <div class="form-group">
        <label for="gender">性别:</label>
        <select id="gender" v-model="userInfo.gender" required>
          <option value="Male" :selected="userInfo.gender === 'Male'">男</option>
          <option value="Female" :selected="userInfo.gender === 'Female'">女</option>
        </select>
      </div>
      <div class="form-group">
        <label for="user-image">上传头像:</label>
        <input type="file" id="user-image" @change="handleImageUpload" />
      </div>
      <div v-if="imagePreview" class="image-preview">
        <img :src="imagePreview" alt="头像预览" />
      </div>
      <BaseButton variant="primary" size="large" type="submit" >更新信息</BaseButton>
    </form>
  </div>
</template>

<script setup>
import {onMounted, reactive, ref} from 'vue'
import BaseButton from '@/components/BaseButton.vue'
import {useUserStore} from "@/store/user"
import axios from '@/axios'

// 定义响应式数据
const userStore = useUserStore()
const userImage = ref('')
let userInfo = reactive({
  gender: 'Male',
  password: '',
  username: '',
  email: '',
  age: '',
  role: ''

})

const initialUserInfo = { ...userInfo }  // 保存初始的用户信息

const imagePreview = ref(null)

axios.get("/user/userInfo").then(res => {
  userInfo.username = res.data.data.username
  userInfo.email = res.data.data.email
  userInfo.gender = res.data.data.gender
  userInfo.age = res.data.data.age
  userInfo.role = res.data.data.role
  userInfo.password = res.data.data.password
})

// 处理头像上传
const handleImageUpload = (event) => {
  const file = event.target.files[0]
  if (file) {
    userImage.value = file
    imagePreview.value = URL.createObjectURL(file)
  }
}

// 提交表单时调用此函数
const handleUpdateProfile = async () => {
  // 检查是否有需要更新的字段
  const hasChanges = userInfo.username !== initialUserInfo.username ||
      userInfo.email !== initialUserInfo.email ||
      userInfo.gender !== initialUserInfo.gender

  if (!hasChanges && !userImage.value) {
    // 如果没有字段变化且没有选择头像，不执行任何操作
    alert('没有任何更新')
    return
  }

  try {
    // 如果头像有更新
    if (userImage.value) {
      const formData = new FormData()
      formData.append('touUrl', userImage.value)

      const uploadResponse = await axios.patch('/user/updateTou', formData, {
        headers: {
          'Content-Type': 'multipart/form-data',
        }
      })
      if (uploadResponse.data?.message === '操作成功') {
        userStore.updateUserImage(uploadResponse?.data?.data?.touUrl)
        console.log(userStore.userImage)
        if(!hasChanges) {
          alert("头像上传成功")
        }
      }
    }

    // 如果有字段变化，执行更新请求
    if (hasChanges) {
      const response = await axios.put('/user/update', userInfo, {
        headers: {
          'Content-Type': 'application/json',
        }
      })

      if (response.data.code === 0) {
        alert('个人信息更新成功')
        // 更新成功后，保存当前用户信息为初始值
        Object.assign(initialUserInfo, userInfo)
      }
    }

    // 清除表单
    imagePreview.value = null
    userImage.value = null
  } catch (error) {
    console.error('个人信息更新失败:', error)
  }
}
const clearInput = (field) => {
  userInfo[field] = '';  // 清空输入框内容
};

const restorePlaceholder = (field) => {
  if (!userInfo[field]) {
    // 如果内容为空，则恢复占位符
    userInfo[field] = userStore[field];
  }
};

</script>

<style scoped>
.update-profile {
  height: 100vh;
  width: 80%;
  margin: var(--spacing-large) auto;
  padding: var(--spacing-large);
}

.update-profile h3 {
  text-align: center;
  margin-bottom: var(--spacing-large);
  color: var(--primary-color);
}

.form-group {
  margin-bottom: var(--spacing-large);
  display: flex;
  flex-direction: column;
}

.form-group label {
  display: block;
  margin-bottom: var(--spacing-small);
  font-weight: 600;
  color: var(--text-color);
}

.form-group input {
  width: 100%;
  padding: var(--spacing-small);
  border: 1px solid #bdc3c7;
  border-radius: var(--border-radius);
  font-size: var(--font-size-base);
  box-sizing: border-box;
  transition: border-color 0.3s;
}

.form-group input:focus {
  border-color: var(--secondary-color);
  outline: none;
}

.image-preview {
  text-align: center;
  margin-bottom: var(--spacing-large);
}

.image-preview img {
  max-width: 100%;
  height: auto;
  border-radius: var(--border-radius);
}

/* 使用 BaseButton 组件 */
button {
  width: 100%;
  padding: var(--spacing-small);
  background-color: var(--primary-color);
  color: white;
  border: none;
  border-radius: var(--border-radius);
  font-size: var(--font-size-large);
  cursor: pointer;
  transition: background-color 0.3s;
}

button:hover {
  background-color: var(--secondary-color);
}
</style>
